<?php

namespace App\Services\JWT;

use App\Services\JWT\Lib\JWT;
use App\Services\JWT\Lib\Key;

class JWTService
{
    protected static $key = 'abc_234345465';
    protected static $exp = 7200;

    public static function encode(array $data, int $exp = 7200): string
    {
        $payload = array(
            //  签发者
            "iss"  => "",
            //  面向用户，可以为空
            "aud"  => "",
            // 签发的时间
            //"iat"  => time(),
            // 在什么时候JWT生效？
            //"nbf"  => time(),
            //  token 过期时间
            'exp'  => time() + $exp,
            'jti'  => md5(uniqid('JWT') . time()),  //该Token唯一标识
            //  用户ID
            'data' => $data
        );
        return JWT::encode($payload, self::$key, 'HS256');
    }

    public static function previewToken(array $data, int $exp = 0): string
    {
        $exp = $exp ?: config('preview.preview_expire');
        $payload = array(
            'exp'  => time() + $exp,
            'data' => $data
        );
        return JWT::encode($payload, self::$key, 'HS256');
    }

    public static function decode($jwt): \stdClass
    {
        $jwt = JWT::decode($jwt, new Key(self::$key, 'HS256'));
        return $jwt->data;
    }


}
